<?php

namespace addons\zzuser\controller\api;

use addons\zzuser\model\UserM;
use addons\zzuser\service\EncryptS;
use app\common\controller\Api;
use app\common\library\Sms;
use fast\Random;
use think\Validate;

class PasswordBySms extends Api
{
    protected $noNeedLogin = 'index';
    protected $noNeedRight = 'index';

    public function index()
    {
        $validate = new Validate();
        if (!$validate->check(input(), [
            'password'         => 'require',
            'password_confirm' => 'confirm:password',
            'mobile'           => 'require|regex:1\d{10}',
            'sms'              => 'require',
        ])) {
            $this->error($validate->getError());
        }
        $mobile   = input('mobile');
        $sms      = input('sms');
        $password = input('password');
        if (!Sms::check($mobile, $sms)) {
            $this->error('error sms');
        }
        $user = UserM::where('username', $mobile)->find();
        if (!$user) {
            $this->error();
        }
        $salt = Random::alnum();
        $user->save([
            'salt'     => $salt,
            'password' => EncryptS::password($password, $salt),
        ]);
        $this->success();
    }
}
